package com.dyna.controller;

import com.dyna.bean.CommonsResult;
import com.dyna.bean.Payment;
import com.dyna.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
@Slf4j
public class OrderController {
    public final static String PAYMENT_URL = "http://cloud-provider-payment";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancer loadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

//    下面是80要发送的请求,并且浏览器发get请求
    @GetMapping("/consumer/payment/create")
    public CommonsResult<Payment> create(Payment payment){
//        而这里的url是restTemplate发的请求，第二个是参数payment是请求参数对象，第三个参数是response返回的结果类型
//        但是这里payment虽然传的是对象，但是postForObject这个方法内部做了转换，将其作为了一个json格式发过去了
        return restTemplate.postForObject(PAYMENT_URL+"/add",payment,CommonsResult.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonsResult<Payment> getPayment(@PathVariable("id") Integer id){
        return restTemplate.getForObject(PAYMENT_URL+"/byid/"+id,CommonsResult.class);
    }

    @GetMapping("/consumer/payment/getEntity/{id}")
    public CommonsResult<Payment> getPayment2(@PathVariable("id") Integer id){
        ResponseEntity<CommonsResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/byid/" + id, CommonsResult.class);
        if (entity.getStatusCode().is2xxSuccessful()){
            return entity.getBody();
        }else {
            return new CommonsResult<>(444,"操作失败");
        }
    }

    @GetMapping("/consumer/payment/lb")
    public String getPaymentLB(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER-PAYMENT");
        if (instances==null || instances.size()<=0){
            return null;
        }
//        再这里得到了返回的实例，
        ServiceInstance instance = loadBalancer.instances(instances);
//        然后在这里获取到这个实例的uri信息
        URI uri = instance.getUri();
//        传一个服务端的uri，再传一个服务端的请求
        return restTemplate.getForObject(uri+"/payment/lb",String.class);
    }

    @GetMapping("/consumer/payment/zipkin")
    public String paymentZipkin()
    {
        String result = restTemplate.getForObject("http://localhost:8001"+"/payment/zipkin/", String.class);
        return result;
    }

}
